﻿using FieldTools.Client.Command;
using FieldTools.Client.Model.Window;
using FieldTools.Client.Entity;
using FieldTools.Client.Entity.MyQQ;
using FieldTools.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using MessageBox = HandyControl.Controls.MessageBox;
using FieldTools.Util.Helper;
using FieldTools.Client.Entity.Model;

namespace FieldTools.Client.ViewModel.Window
{
    /// <summary>
    /// MyQQ框架对接视图模型
    /// </summary>
    public class MyQQViewModel : NotificationObject, ISingletonDependency
    {
        /// <summary>
        /// 
        /// </summary>
        public MyQQViewModel()
        {
            //obj = CacheHelper.GetCache<MyQQModel>(nameof(MyQQModel));
            //配置初始化
            obj = CacheHelper.GetOrSetCache(nameof(MyQQModel), new MyQQModel());
            if(obj.RobotMasters == null || obj.RobotMasters.Count == 0)
            {
                obj.RobotMasters = [
                    new() {
                        RobotQQ = "1234567",
                        MasterQQ = "12345678",
                        
                    }];
            }
            if (obj.CustonOrders == null || obj.CustonOrders.Count == 0)
            {
                obj.CustonOrders = [
                    new(){
                        Keyword = "#FieldTool",
                        ScriptContent = "自定义脚本测试回复成功",
                        IsOn = false,
                        Remark = "" 
                    }];
            }
            if(obj.OnebotConfig == null)
            {
                obj.OnebotConfig = new();
            }
            //装载自动任务,todo

        }

        #region 实体
        public MyQQModel obj { get; set; }

        /// <summary>
        /// 是否从线上获取数据
        /// </summary>
        public bool IsOnlineGetInfo
        {
            get
            {
                return obj.OnlineGetInfoTagForMyQQ;
            }
            set
            {
                obj.OnlineGetInfoTagForMyQQ = value;
                GlobalParm.OnlineGetInfoTagForMyQQ = value;
                this.RaisePropertyChanged(nameof(IsOnlineGetInfo));
            }
        }

        public Dictionary<int, string> ScriptTypes => ScriptType.CShape脚本.ToDirctionary<ScriptType>();


        #endregion

        #region 事件

        #region 基础数据操作
        private BaseCommand saveMyQQHttpApiConfig;
        /// <summary>
        /// 保存连接数据
        /// </summary>
        public BaseCommand SaveMyQQHttpApiConfig
        {
            get
            {
                saveMyQQHttpApiConfig ??= new BaseCommand(new Action<object>(o =>
                    {
                        SaveApiConfig();
                    }));
                return saveMyQQHttpApiConfig;
            }
        }

        private BaseCommand refreshMyQQHttpApiConfig;
        /// <summary>
        /// 刷新连接数据
        /// </summary>
        public BaseCommand RefreshMyQQHttpApiConfig
        {
            get
            {
                refreshMyQQHttpApiConfig ??= new BaseCommand(new Action<object>(o =>
                    {
                        RefreshApiConfig();
                    }));
                return refreshMyQQHttpApiConfig;
            }
        }

        private BaseCommand saveOnebotConfig;
        /// <summary>
        /// 保存onebot连接数据
        /// </summary>
        public BaseCommand SaveOnebotConfig
        {
            get
            {
                saveOnebotConfig ??= new BaseCommand(new Action<object>(o =>
                {
                    this.obj.OnebotConfig = this.obj.OnebotConfig;
                }));
                return saveOnebotConfig;
            }
        }


        #endregion

        #region 自定义指令

        private BaseCommand addMyCustomOrder;
        /// <summary>
        /// 添加自定义回复指令
        /// </summary>
        public BaseCommand AddMyCustomOrder
        {
            get
            {
                addMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                    {
                        AddCustomOrder();
                    }));
                return addMyCustomOrder;
            }
        }
        private BaseCommand deleteMyCustomOrder;
        /// <summary>
        /// 删除自定义回复指令
        /// </summary>
        public BaseCommand DeleteMyCustomOrder
        {
            get
            {
                deleteMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                    {
                        DeleteCustomOrder(o);
                    }));
                return deleteMyCustomOrder;
            }
        }

        private BaseCommand changeMyCustomOrder;
        /// <summary>
        /// 修改自定义指令
        /// </summary>
        public BaseCommand ChangeMyCustomOrder
        {
            get {
                changeMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                {
                    ChangeCustomOrder(o);
                }));
                return changeMyCustomOrder; 
            }
        }

        #endregion

        #region QQ关联

        private BaseCommand addMyRobotMaster;
        /// <summary>
        /// 添加QQ关联
        /// </summary>
        public BaseCommand AddMyRobotMaster
        {
            get
            {
                addMyRobotMaster ??= new BaseCommand(new Action<object>(o =>
                    {
                        AddRobotMaster();
                    }));
                return addMyRobotMaster;
            }
        }
        private BaseCommand deleteMyRobotMaster;
        /// <summary>
        /// 删除QQ关联
        /// </summary>
        public BaseCommand DeleteMyRobotMaster
        {
            get
            {
                deleteMyRobotMaster ??= new BaseCommand(new Action<object>(o =>
                    {
                        DeleteRobotMaster(o);
                    }));
                return deleteMyRobotMaster;
            }
        }

        private BaseCommand changeMyRobotMaster;
        /// <summary>
        /// 修改机器人管理员关联
        /// </summary>
        public BaseCommand ChangeMyRobotMaster
        {
            get
            {
                changeMyRobotMaster ??= new BaseCommand(new Action<object>(o =>
                {
                    ChangeRobotMaster(o);
                }));
                return changeMyRobotMaster;
            }
        }
        #endregion

        #region js脚本执行
        private BaseCommand openFile;
        /// <summary>
        /// 打开js文件
        /// </summary>
        public BaseCommand OpenFile
        {
            get
            {
                if (openFile == null)
                {
                    openFile = new BaseCommand(new Action<object>(o =>
                    {
                        obj.JsFilePath = ChooseFile();
                    }));
                }
                return openFile;
            }
        }
        #endregion
        #endregion

        #region 功能方法
        #region 通信配置相关
        /// <summary>
        /// 保存httpApi配置，暂时仅处理一个框架，后续有需求在做多框架
        /// </summary>
        /// <returns></returns>
        private void SaveApiConfig()
        {
            try
            {
                if (obj!=null)
                {
                    CacheHelper.SetCache(nameof(MyQQModel), obj);
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show("配置文件异常");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败" + ex);
            }
        }
        /// <summary>
        /// 刷新httpApi配置
        /// </summary>
        private void RefreshApiConfig()
        {
            try
            {
                var jsonObj = CacheHelper.GetCache(nameof(MyQQModel));
                if(jsonObj != null)
                {
                    obj = jsonObj.ToString().ToObject<MyQQModel>();
                    MessageBox.Show("刷新成功");
                }
                else
                {
                    MessageBox.Show("缓存配置为空，请重启初始化配置");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("刷新失败：" + ex);
            }
        }
        #endregion

        #region 自定义指令相关
        /// <summary>
        /// 添加自定义回复指令
        /// </summary>
        private void AddCustomOrder()
        {
            if(obj.CustonOrders==null || obj.CustonOrders.Count == 0)
            {
                obj.CustonOrders = [];
            }
            obj.CustonOrders?.Add(new()
            {
                Keyword = "(请修改)",
                ScriptContent = "(请修改)",
                IsOn = false,
                Remark = ""
            });
        }
        /// <summary>
        /// 删除指令表格数据
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteCustomOrder(object? obj)
        {
            try
            {
                if (obj == null)
                    return;
                if (obj is not DataGrid dataGrid) return;

                MessageBoxResult result = MessageBox.Show("是否删除当前选择项？", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var selectedItems = (dataGrid?.SelectedItems).ToJson().ToObject<List<OrderData>>();
                    var orders = this.obj.CustonOrders?.ToList();
                    selectedItems?.ForEach(o =>
                    {
                        var index = orders?.FindIndex(x => x.Id == o.Id);
                        if (index != null && index != -1)
                        {
                            this.obj.CustonOrders?.RemoveAt((int)index);
                        }
                    });
                    MessageBox.Show("数据删除成功，请注意保存");
                }
                else if (result == MessageBoxResult.No)
                {
                    //不删除
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据删除失败：" + ex);
            }

        }
        /// <summary>
        /// 修改自定义指令
        /// </summary>
        /// <param name="o"></param>
        private void ChangeCustomOrder(object? o)
        {
            if (o == null)
                return;
            if (o is not DataGrid dataGrid) return;
            var items = dataGrid.ItemsSource.CastToList<OrderData>();
            if (items != null)
            {
                obj.CustonOrders = new(items);
            }
        }
        #endregion

        #region QQ关联绑定相关
        /// <summary>
        /// 添加QQ关联
        /// </summary>
        private void AddRobotMaster()
        {
            if(obj.RobotMasters==null || obj.RobotMasters.Count == 0)
            {
                obj.RobotMasters = [];
            }
            obj.RobotMasters?.Add(new()
            {
                RobotQQ = "(请修改)",
                MasterQQ = "(请修改)"
            });
        }
        /// <summary>
        /// 删除QQ关联表格数据
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteRobotMaster(object? obj)
        {
            try
            {
                if (obj == null)
                    return;
                //object[]? multiObj = obj as object[];
                //DataGrid? dataGrid = multiObj?[0] as DataGrid;
                if (obj is not DataGrid dataGrid) return;
                MessageBoxResult result = MessageBox.Show("是否删除当前选择项？", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var selectedItems = (dataGrid?.SelectedItems).ToJson().ToObject<List<RobotMaster>>();
                    var robotMasters = this.obj.RobotMasters?.ToList();
                    selectedItems?.ForEach(o =>
                    {
                        var index = robotMasters?.FindIndex(x => x.Id == o.Id);
                        if (index != null && index != -1)
                        {
                            this.obj.RobotMasters?.RemoveAt((int)index);
                        }
                    });
                    //MessageBox.Show("数据删除成功，请注意保存");
                }
                else if (result == MessageBoxResult.No)
                {
                    //不删除
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据删除失败：" + ex);
            }

        }
        /// <summary>
        /// 求改机器人关联
        /// </summary>
        /// <param name="o"></param>
        private void ChangeRobotMaster(object o)
        {
            if (o == null)
                return;
            if (o is not DataGrid dataGrid) return;
            var items = dataGrid.ItemsSource.CastToList<RobotMaster>();
            if (items != null)
            {
                obj.RobotMasters = new(items);
            }
        }
        #endregion

        #region 自动任务
        /// <summary>
        /// 添加自动任务
        /// </summary>
        private void AddRobotTask()
        {
            if (obj.RobotTasks == null || obj.RobotTasks.Count == 0)
            {
                obj.RobotTasks = [];
            }
            obj.RobotTasks?.Add(new()
            {
                //Keyword = "(请修改)",
                ScriptContent = "(请修改)",
                IsOn = false,
                Remark = ""
            });
        }
        /// <summary>
        /// 删除指令表格数据
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteCustomOrder(object? obj)
        {
            try
            {
                if (obj == null)
                    return;
                if (obj is not DataGrid dataGrid) return;

                MessageBoxResult result = MessageBox.Show("是否删除当前选择项？", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var selectedItems = (dataGrid?.SelectedItems).ToJson().ToObject<List<OrderData>>();
                    var orders = this.obj.CustonOrders?.ToList();
                    selectedItems?.ForEach(o =>
                    {
                        var index = orders?.FindIndex(x => x.Id == o.Id);
                        if (index != null && index != -1)
                        {
                            this.obj.CustonOrders?.RemoveAt((int)index);
                        }
                    });
                    MessageBox.Show("数据删除成功，请注意保存");
                }
                else if (result == MessageBoxResult.No)
                {
                    //不删除
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据删除失败：" + ex);
            }

        }
        /// <summary>
        /// 修改自定义指令
        /// </summary>
        /// <param name="o"></param>
        private void ChangeCustomOrder(object? o)
        {
            if (o == null)
                return;
            if (o is not DataGrid dataGrid) return;
            var items = dataGrid.ItemsSource.CastToList<OrderData>();
            if (items != null)
            {
                obj.CustonOrders = new(items);
            }
        }
        #endregion

        #region js执行
        private static string ChooseFile()
        {
            var ofd = new Microsoft.Win32.OpenFileDialog() { Filter = "JS脚本文件 (*.js)|*.js" };
            var result = ofd.ShowDialog();
            if (result == false) return "";
            else
            {
                return ofd.FileName;
            }
        }
        #endregion


        #endregion
    }
}
